package com.fruits.manage.web.controller;

import java.util.HashMap;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

/**
 * 超级控制器
 * 
 * @author chenxl
 * 
 * @date 2015-1-16
 * @time 下午06:10:22
 */
public abstract class ControllerSupport extends Controller {

	/** 实体类 */
	protected abstract Model<?> getDao();

	/** 别名 */
	protected abstract String getAlias();
	
	/** model名称 */
	protected String getModelName() {
		return getDao().getClass().getSimpleName().toLowerCase();
	}
	
	/**
	 * 当前映射的表信息
	 * @return
	 */
	protected Table getTable() {
		return TableMapping.me().getTable(getDao().getClass());
	}
	
	/**
	 * 保存/更新
	 */
	public void save() {
		Model<?> model = this.getModel(getDao().getClass());
		String isSucc = "ok";
		try {
			if (StrKit.isBlank(model.getStr("id"))) {
				//this.getModel(getDao().getClass(), getAlias()).set("id", IDUtils.uuid32()).save();
			} else {
				this.getModel(getDao().getClass()).update();
			}
		} catch (Exception e) {
			isSucc = "err";
			e.printStackTrace();
		}
		renderText(isSucc);
	}
	
	public void update() {
		getModel(getDao().getClass(), getAlias()).update();
		renderText("update 1");
	}

	/**
	 * 删除
	 */
	public void delete() {
		String dm = getPara(0);
		if (StrKit.notBlank(dm)) {
			getDao().deleteById(dm);
		}
	}
	
	/**
	 * 删除多个主键
	 */
	public void delByZjs() {
		String zj = getPara(0);
		if (StrKit.notBlank(zj)) {
			StringBuffer sb = new StringBuffer();
			sb.append(" delete from ").append(getTable().getName());
			sb.append(" where zj in('").append(zj.replace(",", "','")).append("')");
			Db.update(sb.toString());
		}
		renderText("ok");
	}
	
	/**
	 * 查找单位对象
	 */
	public void findById() {
		Model<?> model = getDao().findById(getPara(0));
		renderJson(model);
	}
	
	/**
	 * 跳转到form页面
	 */
	public void form() {
		String zj = getPara(0);
		if (!StrKit.isBlank(zj)) {
			setAttr(getAlias(), getDao().findById(zj));
		}
		renderJsp("/pages/model/" + getModelName() + "/" + getModelName() + "_insert.jsp");
	}
	
	/**
	 * 分页
	 * @param select
	 * @param sqlExceptSelect
	 * @param arr
	 */
	@SuppressWarnings("unchecked")
	public void paginate(String select, String sqlExceptSelect, Object... arr) {
		int pageNumber = getParaToInt("page") == null ? 1 : getParaToInt("page");
		int pageSize = getParaToInt("rows");
		String json = "";
		try {
			Page<Model<?>> paging = (Page<Model<?>>) getDao().paginate(pageNumber, pageSize, select, sqlExceptSelect, arr);
			
			Map<String, Object> jsonMap = new HashMap<String, Object>();
			jsonMap.put("total", paging.getTotalRow());
			jsonMap.put("rows", paging.getList());
			json = JsonKit.toJson(jsonMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		renderText(json);
	}

}
